/*
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
*/

class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        int sum_closest = INT_MAX, diff_closest = INT_MAX;
        sort(num.begin(), num.end());
        for (int i = 0; i < num.size() - 2; i++) {
            int sum_2, sum_2_closest = INT_MAX, diff_2_closest = INT_MAX;
            int target_2 = target - num[i];
            for (int j = i+1, k = num.size()-1; j<k; ) {
                int sum = num[i] + num[j] + num[k];
                if (sum < target) j++;
                else if (sum > target) k--;
                else return target; // shortcut (return immediately)
                int diff_abs = abs(sum-target);
                if (diff_abs < diff_closest) {
                    diff_closest = diff_abs;
                    sum_closest = sum;
                }
            }
        }
        return sum_closest;
    }
};

#if 0
class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        int sum_closest = INT_MAX, diff_closest = INT_MAX;
        int len = (int)num.size();
        sort(num.begin(), num.end());
        for (int i = 0; i < len - 2; i++) {
            int sum_2, sum_2_closest = INT_MAX, diff_2_closest = INT_MAX;
            int target_2 = target - num[i];
            for (int j = i+1, k = len-1; j<k; ) {
                sum_2 = num[j] + num[k];
                if (sum_2 == target_2) {
                    // shortcut , return immediately
                    return target;
                } else if (sum_2 < target_2) {
                    j++;
                } else {
                    k--;
                }
                int diff_2_abs = abs(sum_2 - target_2);
                if (diff_2_abs < diff_2_closest) {
                    diff_2_closest = diff_2_abs;
                    sum_2_closest = sum_2;
                }
            }
            if (diff_2_closest < diff_closest) {
                diff_closest = diff_2_closest;
                sum_closest = sum_2_closest + num[i];
            }
        }
        return sum_closest;
    }
};
#endif
